<?php
class blogpage extends page{
	public $userId;
	public $userNumber;
	public $blogKinds;
	public $blogId;
	public $blog;
	public $editor;//新增，更新判别标志
	public $draftId;
	
	public function __construct(){
		parent::__construct();
		$this->editor = 0;
		$this->userNumber = $_SESSION["userNumber"];
		$this->userId =$_SESSION["userId"];
		$uerNumber =$this->userNumber;
		$this->title = "写新博客——".$uerNumber."的博客";
		$blogKinds = $this->getBlogKind($this->userId);
		if(empty($blogKinds)){
			$kind ="默认";
			$this->insertNewBlogKind($this->userId,$kind);
			$this->blogKinds = $this->getBlogKind($this->userId);
		}
		else {
			$this->blogKinds = $blogKinds;
		}
		$this->draftId =$this->getBlogDraftId();
		$post = $_POST;
		if(!empty($post)){
			//将新内容提交到数据库
			$this->submitDiary($post);
			
		}
		
		//更新博客
		$blogId = $_GET["blogId"];
		if($blogId){
			$this->editor =1;
			$this->blogId = $blogId;
			$this->blog = $this->getBlog($blogId);
		}
		
		
	}
	public function submitDiary($data){
		$title = $this->formDataFilter($data["title"]);
		$kind = $this->formDataFilter($data["kind"]);
		$content =$data["editor1"];
		$quanxian = $data["quanxian"];
		$postdate = date("Y-m-d H:i:s");
		$postType =$data["postType"];
		$userId = $this->userId;
		$dao=new blogdao();
		if($postType==0){
			$addNewBlog = $dao->goAddNewBlog($title,$kind,$content,$postdate,$userId,$quanxian);
			if ($addNewBlog!=""){
				echo "<script>alert('发表成功！');window.location.href='bloglist.php?blogId=$addNewBlog'</script>";
			}
			else {
				echo "<script>alert('发表失败！');return false;</script>";
			}
		}
		else if($postType==1){
			$blogId =$data["blogId"];
			$updateBlog = $this->updateBlog($title,$kind,$content,$postdate,$userId,$quanxian,$blogId);
			if ($updateBlog){
				echo "<script>alert('更新成功！');window.location.href='bloglist.php?blogId=$blogId'</script>";
			}
			else {
				echo "<script>alert('更新失败！');window.location.href='blog.php?blogId=$blogId';</script>";
			}
		}
	}
	public function getBlogKind($userId){
		$dao=new blogdao();
		$kinds =$dao->goGetBlogKind($userId);
		return $kinds;
	}
	public function insertNewBlogKind($userId,$kind){
		$dao = new blogdao();
		$insert = $dao->goInsertNewBlogKind($userId,$kind);
		return $insert;
	}
	public function getBlog($blogId){
		$dao = new blogdao();
		$blog = $dao->goGetBlog($blogId);
		return $blog;
		
	}
	public function updateBlog($title,$kind,$content,$postdate,$userId,$quanxian,$blogId){
		$dao =new blogdao();
		$query = $dao->goUpdateBlog($title,$kind,$content,$postdate,$userId,$quanxian,$blogId);
		return $query;
	}
	public function getBlogDraftId(){
		$dao =new blogdao();
		$draftId = $dao->goGetBlogDraftId($this->userId);
		return $draftId;
	}
	
}
?>